//
//  EnterpriseListView.m
//  WRY
//
//  Created by zhong sckj on 10-10-15.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "EnterpriseListView.h"
#import "CommonJson.h"
#import "AppDelegate_iPad.h"
#import "WebPath.h"
#import "EnterpriseListCell_iPad.h"
#import "StaticVariable.h"
#import "RootVC_iPad.h"

#define LEFTVIEWHEIGHT 644

//全局变量
extern NSString *namecode;
extern NSString *nameStr;

@implementation EnterpriseListView

@synthesize enterpriseListT,listData;
@synthesize _cell,pageCell,pageButton;
@synthesize methodName,enterpriseTypeCode,detailTypeCode;
@synthesize listVcController,rootVc;

//@synthesize entersDir;
//@synthesize enterdirKeys;
@synthesize mytimer;
//@synthesize methodName,enterpriseTypeCode,detailtypeCode,selectNameCode,dayCount;


- (void)requestForRegion:(NSString *)body methodName:(NSString *)mthod {
	[self showLoading];
	NSString *bodyStr = [NSString stringWithFormat:@"LoginGuid=%@&%@",[[AppDelegate_iPad currentDelegate] GUID],body];
	bodyStr = [bodyStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	[[CommonJson sharedInstance] requestToPath:[WebPath enterprisePath]
									methodName:mthod 
									bodyString:bodyStr 
									 targetObj:self
							  targetMethodName:@"eventForRequest:"
									notifiName:@"Page_enterpriseList"];
	
}
- (void)eventForRequest:(NSNotification *)notification {
	[self hideLoading];
	[[CommonJson sharedInstance] removeTarget:self notiName:[notification name]];
	NSObject *object  = [notification object];
	if ([object isKindOfClass:[NSDictionary class]]) {
		NSDictionary *dict = (NSDictionary *)object;
		if ([[dict objectForKey:@"Status"] intValue]==1) 
		{
			if ([[dict objectForKey:@"Data"] isKindOfClass:[NSDictionary class]])
			{
				NSDictionary  *enterlist=(NSDictionary *)[dict objectForKey:@"Data"];
				
				NSArray *enterlistArray=(NSArray *)[enterlist objectForKey:@"EntityList"];
				[listData addObjectsFromArray:enterlistArray];
							
				NSString *count =[enterlist objectForKey:@"RecordCount"];
				enlistTotalCount = [count intValue];
				//pageCount=enlistTotalCount%pageSize==0?enlistTotalCount/pageSize:(enlistTotalCount/pageSize)+1;
				if (enlistTotalCount > [listData count] )
				{
					[pageButton setHidden:NO];
					[self.pageButton setTitle:[NSString stringWithFormat:@"显示更多(还有%u条)",enlistTotalCount-[listData count]] forState:UIControlStateNormal];
				}
                else{
                    [pageButton setHidden:YES];

                }
				[enterpriseListT reloadData];
				
				if (listVcController!=nil) {
					if (listVcController.isMapLoad) {
						[listVcController setMapPorperites];
					}
					
				}
				
				
			}
			else {
				//[self showConnectionError];
			}
		}
		else {
			//[self showConnectionError];
		}
		
	}
	else {
		//[self showConnectionError];
	}	
}
-(void)fillData:(NSString *)methodNameStr
 selectNameCode:(NSString *)nameCodeStr 
enterpriseTypeCode:(NSString *)enterprisetypeCodeStr
 DetailTypeCode:(NSString *)detailTypeCodeStr
{
	NSString *body;
	if ([methodNameStr isEqualToString:@"Page__EnterpriseListCantonRealTime"])
	{
		//detailTypeCodeStr=@"-1";
		body = [NSString stringWithFormat:@"PageSize=%@&PageNow=%@&CantonCodes=%@&EnterpriseTypeCodes=%@&DetailTypeCode=%@"
				,[NSString stringWithFormat:@"%ld",(long)pageSize],[NSString stringWithFormat:@"%ld",(long)pagecurrentCount],nameCodeStr,enterprisetypeCodeStr,detailTypeCodeStr];
	}
	else if([methodNameStr isEqualToString:@"Page__EnterpriseListVocationRealTime"]) {
		body = [NSString stringWithFormat:@"PageSize=%@&PageNow=%@&VocationCode=%@&EnterpriseTypeCodes=%@&DetailTypeCode=%@"
				,[NSString stringWithFormat:@"%ld",(long)pageSize],[NSString stringWithFormat:@"%ld",(long)pagecurrentCount],nameCodeStr,enterprisetypeCodeStr,detailTypeCodeStr];
	}
	else {
		body = [NSString stringWithFormat:@"PageSize=%@&PageNow=%@&PsLevelCode=%@&EnterpriseTypeCodes=%@&DetailTypeCode=%@"
				,[NSString stringWithFormat:@"%ld",(long)pageSize],[NSString stringWithFormat:@"%ld",(long)pagecurrentCount],nameCodeStr,enterprisetypeCodeStr,detailTypeCodeStr];
	}

	//NSLog(@"%@",[NSString stringWithFormat:@"%@%@",methodName,body]);
	[self requestForRegion:body methodName:methodNameStr];
}
#pragma mark enterListView被不同地方用到
- (id)initWithFrame:(CGRect)frame loadFromType:(NSInteger)fromtype entertype:(NSInteger)entertype {
    if ((self = [super initWithFrame:frame]))
	{
		listData = [[NSMutableArray alloc] init];
		[self createTableView];	
		[self initRightView];
		
		loadFromType=fromtype;
		wuyEnterType=entertype;
		
		enlistTotalCount=0;
		pagecurrentCount=1;
		pageSize=20;
		self.enterpriseTypeCode=@"";
		self.detailTypeCode=@"0";
		//默认加载数据
//		NSString *namecodestr;
//		if (fromtype==1) 
//		{
//			namecodestr=@"";
//			self.methodName=@"Page__EnterpriseListCantonRealTime";
//		}
//		else 
//		{
//			if (wuyEnterType==1000) 
//			{
//				self.methodName=@"Page__EnterpriseListCantonRealTime";
//			}
//			else if(wuyEnterType==2000) {
//				self.methodName=@"Page__EnterpriseListVocationRealTime";
//			}
//			else {
//				self.methodName=@"Page__EnterpriseListLevelRealTime";
//			}
//
//
//			namecodestr=namecode;
//		}
		
		
		//entersDir=[[NSMutableDictionary alloc]init];
		mytimer=[NSTimer scheduledTimerWithTimeInterval:2 target:self 
											   selector:@selector(timerAction:) 
											   userInfo:nil repeats:YES];
		
		
		
		
		//[self fillData:self.methodName
//		selectNameCode:namecodestr
//	enterpriseTypeCode:self.enterpriseTypeCode
//		DetailTypeCode:self.detailTypeCode];
    }
    return self;
}
#pragma mark 给上层刷新使用
-(void)reflurbish:(NSInteger)fromtype enterType:(NSString *)enterpriseType
{
	[listData removeAllObjects];
	pagecurrentCount=1;
	NSString *methodNameStr;
	//判断是调用行政区还是行业类别
	if (fromtype==1000)
		methodNameStr=@"Page__EnterpriseListCantonRealTime";
	else if(fromtype==2000)
		methodNameStr=@"Page__EnterpriseListVocationRealTime";
	else 
		methodNameStr=@"Page__EnterpriseListLevelRealTime";
	self.methodName=methodNameStr;
	self.enterpriseTypeCode=enterpriseType;
	[self reloadTableView];	
}
-(void)reloadTableView
{
	
	NSString *namecodestr;
	if (loadFromType==1) 
		namecodestr=@"";
	else {
		namecodestr=namecode;
	}
	[self fillData:self.methodName 
	selectNameCode:namecodestr 
enterpriseTypeCode:self.enterpriseTypeCode DetailTypeCode:self.detailTypeCode];
	
}


#pragma mark segmentBUtton
#pragma mark 创建segmentBUtton
-(void)createShiSButton:(UIView *)rightView 
			souceButton:(UIButton *)btn
			   btnTitle:(NSString *)btnTitle
			buttonImage:(UIImage *)btnImage
				 btnTag:(NSInteger)btnTag
			buttonFrame:(CGRect)buttonFrame
{
	btn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
	btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
	[btn setBackgroundImage:btnImage forState:UIControlStateNormal];
	
	[btn setTitle:btnTitle forState:UIControlStateNormal];
	[btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
	//
	btn.tag=btnTag;
	[btn addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventTouchUpInside];
	
	[rightView addSubview:btn];
	[btn release];
	
}
-(void)initRightView
{
	UIView *topview=[[UIView alloc]initWithFrame:CGRectMake(0,0,self.frame.size.width,41)];
	CGRect btnframe;
	//创建segemntcontrollerBUtton
	//正常
	btnframe=CGRectMake(0, 0, 95, 41);
	UIButton *zhengchangbutton=[[UIButton alloc]initWithFrame:btnframe];
	[self createShiSButton:topview 
			   souceButton:zhengchangbutton
				  btnTitle:@"正常" buttonImage:[UIImage imageNamed:@"btn95X41_1.png"] 
					btnTag:200
			   buttonFrame:btnframe];
	//超标
	btnframe=CGRectMake(95, 0, 94, 41);
	UIButton *chaobiaobutton=[[UIButton alloc]initWithFrame:btnframe];
	[self createShiSButton:topview 
			   souceButton:chaobiaobutton
				  btnTitle:@"超标"
			   buttonImage:[UIImage imageNamed:@"btn94X41.png"]
					btnTag:300
			   buttonFrame:btnframe];
	//故障或停产 
	btnframe=CGRectMake(189, 0, 95, 41);
	UIButton *zhuzhangbutton=[[UIButton alloc]initWithFrame:btnframe];
	[self createShiSButton:topview 
			   souceButton:zhuzhangbutton
				  btnTitle:@"离线" 
			   buttonImage:[UIImage imageNamed:@"btn95X41_3.png"]
					btnTag:400
			   buttonFrame:btnframe];
	
	[self addSubview:topview];
	[topview release];
}
-(void)createTableView
{
	UIImageView *borderView=[[UIImageView alloc]initWithFrame:CGRectMake(0,35,self.frame.size.width, LEFTVIEWHEIGHT-41)];
	[borderView setImage:[UIImage imageNamed:@"sidebar285x71_1.png"]];
	borderView.userInteractionEnabled = YES;
	
	enterpriseListT=[[UITableView alloc]initWithFrame:CGRectMake(1.0,8,borderView.frame.size.width-2,LEFTVIEWHEIGHT-43)];
	enterpriseListT.delegate=self;
	enterpriseListT.dataSource=self;
	[borderView addSubview:enterpriseListT];
	[self addSubview:borderView];
	[borderView release];
}
#pragma mark -
#pragma mark 点击正常，超标，故障停产的按钮
-(void)segmentAction:(id)sender
{
	[listData removeAllObjects];
	pagecurrentCount=1;
	UIButton *btn=(UIButton *)[self viewWithTag:200];
	[btn setBackgroundImage:[UIImage imageNamed:@"btn95X41.png"] forState:UIControlStateNormal];
	btn=(UIButton *)[self viewWithTag:300];
	[btn setBackgroundImage:[UIImage imageNamed:@"btn94X41.png"] forState:UIControlStateNormal];
	btn=(UIButton *)[self viewWithTag:400];
	[btn setBackgroundImage:[UIImage imageNamed:@"btn95X41_3.png"] forState:UIControlStateNormal];
	
	btn=(UIButton *)sender;
	if (btn.tag==200) 
	{
		//正常
		[btn setBackgroundImage:[UIImage imageNamed:@"btn95X41_1.png"] forState:UIControlStateNormal];
		self.detailTypeCode=@"0";
	}
	if (btn.tag==300)
	{
		//超标 
		[btn setBackgroundImage:[UIImage imageNamed:@"btn94X41_1.png"] forState:UIControlStateNormal];
		self.detailTypeCode=@"1";
	}
	if (btn.tag==400) 
	{
		//故障停产
		[btn setBackgroundImage:[UIImage imageNamed:@"btn95X41_4.png"] forState:UIControlStateNormal];
		self.detailTypeCode=@"2";
	}
	//[listVcController linkData];
	[self reloadTableView];	
	
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	if (enlistTotalCount>[listData count] && [listData count]>0) {
		return 2;
	}
	else 
		return 1;
}

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
	if (section==1) {
		if (enlistTotalCount) {
			return 1;
		}
		return 0;
	}
	else 
	{
		return [listData count];
	}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *Listidentifier_ipad = @"enterpriseListCell_iPad";
	if (indexPath.section==1) 
	{
		return pageCell;
		
	}else {
		EnterpriseListCell_iPad *cell=(EnterpriseListCell_iPad *)[tableView dequeueReusableCellWithIdentifier:Listidentifier_ipad];
		if(cell == nil) 
		{
			[[NSBundle mainBundle] loadNibNamed:@"EnterpriseListCell_iPad" owner:self options:nil];
			cell=_cell;
			cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
		}
		if (listData!=nil && [listData count]>indexPath.row) 
		{
			
			NSDictionary *dict = [listData objectAtIndex:indexPath.row];
			cell.nameLabel.text = [dict objectForKey:@"EnterpriseName"];
			
			NSString *enterpriseType=[NSString stringWithFormat:@"%@",[dict objectForKey:@"EnterpriseType"]];
			if ([enterpriseType isEqualToString:@"01"]) {
				cell.enterImageView.image=[UIImage imageNamed:@"entypewater2.png"];
			}
			else if([enterpriseType isEqualToString:@"02"])
			{
				cell.enterImageView.image=[UIImage imageNamed:@"entypeair2.png"];
			}
			else if([enterpriseType isEqualToString:@"03"])
			{
				cell.enterImageView.image=[UIImage imageNamed:@"entypesewage.png"];
			}
			//cell.enterImageView.image=[UIImage imageNamed:@"image78.png"];
			//企业状态
			NSString *enterpriseState=[dict objectForKey:@"EnterpriseState"];
			cell.enterpriseState=enterpriseState;
			cell.currentIndex = 0; 
			NSArray *array = [dict objectForKey:@"EntityList"];
			if (![array isKindOfClass:[NSNull class]]) {
				if ([array count]) {
					cell.dataArray = array;
					[cell changeText];
				}
			}
		}
		
		return cell;
	}
}
#pragma mark 时钟控制器方法
-(void)timerAction:(NSTimer*)theTimer
{
	if ([enterpriseListT numberOfSections] > 0 && [enterpriseListT numberOfRowsInSection:0] > 0) 
	{
		for (int i = 0; i < [listData count]; i++)
		{
			NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
			EnterpriseListCell_iPad *cell =(EnterpriseListCell_iPad *)[enterpriseListT cellForRowAtIndexPath:indexPath];
			cell.currentIndex++;
			[cell changeText];
		}
		
	}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	if (indexPath.section == 1) {
		return;
	}
	if (listData !=nil && [listData count]>indexPath.row) {
		NSDictionary *dict = [listData objectAtIndex:indexPath.row];
		NSString *comaycode=[dict objectForKey:@"EnterpriseCode"];
        NSString *companyTypeCode=[dict objectForKey:@"EnterpriseType"];
		EnterpriseListCell_iPad *listCell=(EnterpriseListCell_iPad *)[enterpriseListT cellForRowAtIndexPath:indexPath];
		//排放口及因子
		NSArray *array = [dict objectForKey:@"EntityList"];	
		NSDictionary *factorydirect=nil;
		if (![array isKindOfClass:[NSNull class]] && array!=nil && [array count]>0) {
			if ([array count]>listCell.currentIndex) {
				factorydirect=[array objectAtIndex:listCell.currentIndex];
				[rootVc addcompanydeatilVC:comaycode companyTypeCode:companyTypeCode 
                                  siteCode:[factorydirect objectForKey:@"SiteCode"] 
                              sitetypeCode:[factorydirect objectForKey:@"SiteType"] 
                               factoryCode:[factorydirect objectForKey:@"StCode"]];	
			}
			
			
		}
		else {
			[rootVc addcompanydeatilVC:comaycode companyTypeCode:companyTypeCode 
                              siteCode:@"" 
                          sitetypeCode:@""
                           factoryCode:@""];	
		}
	}
	
	
}
//-(IBAction)prePageAction
//{
//	if (pagecurrentCount>1) {
//		pagecurrentCount--;
//		[self reloadTableView];
//	}
//	
//}
//-(IBAction)nextPageAction
//{
//	if (pagecurrentCount<pageCount) {
//		pagecurrentCount++;
//		[self reloadTableView];
//	}
//	
//}
-(IBAction)morePageCount
{
	pagecurrentCount++;
	[self reloadTableView];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 50.0;
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)dealloc {
	//[enterdirKeys release];
	//[entersDir release];
	
	[rootVc release];
	[pageCell release];
	[pageButton release];
	[listVcController release];
	//[_cell release];
	[detailTypeCode release];
	[enterpriseTypeCode release];
	[methodName release];
	//[enterpriseListT release];
	[listData release];
    [super dealloc];
}


@end
